package zkk.com.mengqu.handler;

import android.app.AlertDialog;
import android.app.Application;
import android.content.DialogInterface;
import android.util.Log;
import android.widget.Toast;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import rx.functions.Action1;
import zkk.com.mengqu.manager.APIManager;

/**
 * Created by yanquancong on 2015/4/27.
 */
public class RetrofitErrorHandler implements Action1<Throwable> {

	private Application application;

    private APIManager manager;
	public RetrofitErrorHandler(Application application){
		this.application = application;
        manager = new APIManager();
	}

	@Override
	public void call(Throwable e) {
		if (e == null){
			Log.e("On Call", "Unknow Error, Exception is null");
		}else {
			try {
                int code = e.hashCode();

                switch (code){
                    case 400:
//                        showDialog();
                        break;
                    case 401:
                        Log.w("401", "token過期");
                        Toast.makeText(application, "您的身份已過期，請重新打開應用", Toast.LENGTH_LONG).show();
                        break;
                    case 402:
                        Log.w("402" , "404");

                        break;
                    case 404:
                        Log.w("404" , "404");
                        break;
                    case 422:
                        Log.w("422" , "404");
                        break;
                    case 500:
                        showDialog();
                        Log.w("500" , "服務器錯誤");
                        break;
                    case 504:
                        Toast.makeText(application, "當前無網絡，請檢測網絡後，再試一次", Toast.LENGTH_LONG).show();
                        break;
                }

//                Toast.makeText(application , message , Toast.LENGTH_LONG).show();
			}catch (Exception re ){
				re.printStackTrace();
                Log.w("error" , "" + re.getLocalizedMessage());
//				Toast.makeText(application, re.getLocalizedMessage(), Toast.LENGTH_LONG).show();
			}
		}
	}

    private void showDialog() {
        new AlertDialog.Builder(application.getApplicationContext())
                .setMessage("連接服務器失敗")
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setNegativeButton(android.R.string.cancel ,new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        manager.noToken();
                        dialog.dismiss();
                    }
                })
                .setCancelable(false)
                .show();
    }
}
